package tool;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import work.WordSeg;

public class LCMCMarker {
	public static HashMap<String, String> LCMCSet;
	static final String TrainingFile = "TrainingData.txt";
	static final String MarkedFile = "MarkedTrainingData.txt";
	static final String lookingFor = "^p$|^v$|^a$|^n$|^vn$|^m$";
	static final WordSeg ws = new WordSeg();
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		LCMCReader.resolveData(null);
		LCMCSet = LCMCReader.words;
		Pattern p = Pattern.compile("(?<=\\^)\\w*(?=\\$)");
		Matcher m = p.matcher(lookingFor);
		StringBuilder sb = new StringBuilder();
		while(m.find()){
			sb.append(m.group()+"-");
		}
		mark(TrainingFile, sb.toString() + MarkedFile);

	}

	public static void mark(String input, String output) throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				new FileInputStream(input), "gb2312"));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(
				new FileOutputStream(output), "gb2312"));
		String line = in.readLine();
		int lineCount = 0;
		while (line != null) {
			String marked = markLine(line);
			out.println(marked);
			out.flush();
			// System.out.println(marked);
			System.out.println(++lineCount);
			line = in.readLine();
		}
		in.close();
		out.close();
	}

	private static String markLine(String line) {
		StringBuilder sb = new StringBuilder();
		int start = 0;
		int end = line.indexOf("{", start);
		String tempWords;
		while (start != -1 && end != -1) {
			if (start < end) {
				tempWords = line.substring(start, end);
				markWords(ws.segment(tempWords), sb);
			}
			start = line.indexOf("}", end) + 1;
			sb.append(line.substring(end, start));
			end = line.indexOf("{", start);
		}
		if (start != -1){
			tempWords = line.substring(start, line.length());
			markWords(ws.segment(tempWords), sb);
		}
		return sb.toString();
	}

	private static void markWords(String[] words, StringBuilder sb) {
		for (String word : words) {
			if (LCMCSet.containsKey(word)
					&& LCMCSet.get(word).matches(lookingFor)) {
				sb.append(String.format("{%s/%s}", word, LCMCSet.get(word)));
			} else {
				sb.append(word);
			}
		}
	}

}
